package com.androidhuman.example.MyBookmark;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class BookmarkDB {
	private static final String DATABASE_NAME = "bookmarks.db";
	private static final int DATABASE_VERSION = 1;
	private SQLiteDatabase mDB;
	private DatabaseHelper mDBHelper;
	private Context mCtx;
	
	private class DatabaseHelper extends SQLiteOpenHelper{

		public DatabaseHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(Bookmark.sites._CREATE);
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS "+Bookmark.sites._TABLENAME);
			onCreate(db);
		}
		
	}

	public BookmarkDB(Context context){
		this.mCtx = context;
	}
	
	public BookmarkDB open() throws SQLException{
		mDBHelper = new DatabaseHelper(mCtx, DATABASE_NAME, null, DATABASE_VERSION);
		mDB = mDBHelper.getWritableDatabase();
		return this;
	}
	
	public void close(){
		mDB.close();
	}
	
	public long insertBookmark(String name, String address){
		ContentValues values = new ContentValues();
		values.put(Bookmark.sites.NAME, name);
		values.put(Bookmark.sites.ADDRESS, address);
		return mDB.insert(Bookmark.sites._TABLENAME, null, values);
	}
	
	public boolean updateBookmark(long id, String name, String address){
		ContentValues values = new ContentValues();
		values.put(Bookmark.sites.NAME, name);
		values.put(Bookmark.sites.ADDRESS, address);
		return mDB.update(Bookmark.sites._TABLENAME, values, "_id="+id, null) > 0;
	}
	
	public boolean deleteBookmark(long id){
		return mDB.delete(Bookmark.sites._TABLENAME, "_id="+id, null) > 0;
	}
	
	public Cursor getBookmarks(){
		return mDB.query(Bookmark.sites._TABLENAME, null, null, null, null, null, null);
	}
	
	public Cursor getBookmark(long id){
		Cursor c = mDB.query(Bookmark.sites._TABLENAME, null, 
				"_id="+id, null, null, null, null);
		if(c!=null && c.getCount() != 0)
			c.moveToFirst();
		return c;
	}
}
